package com.tangcco.lockwell.controller.admin;


import com.tangcco.lockwell.service.impl.subjectFileServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@RestController("BatchUploadJsonController")
@RequestMapping(value = "/api/admin/batchUpload",produces = "application/json;charset=UTF-8")
public class BatchUploadJsonController {
    @Resource
    subjectFileServiceImpl subjectService;
    // 处理文件上传的接口
    @PostMapping("/file")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam(name = "fileType", required = false) String fileType) {

        try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            // 创建一个 StringBuilder 对象，用于存储读取的 JSON 内容
            StringBuilder jsonContent = new StringBuilder();
            // 定义一个字符串变量，用于存储读取的每一行数据
            String line;
            // 循环读取文件中的每一行，直到读取完毕
            while ((line = br.readLine())!= null) {
                // 将读取的行内容添加到 jsonContent 中
                jsonContent.append(line);
            }
            String originalFileName = file.getOriginalFilename();
            // 文件名截取
            String name = originalFileName.split("_")[0];
            // 科目截取
            String type = originalFileName.split("_")[1].split("\\.")[0];
            String jsonContentString = jsonContent.toString();
            if (name.equals("政治")){
                System.out.println(name);
                subjectService.politicsUpdate(jsonContentString,type,name);
            }else if (name.equals("英语")){
                System.out.println(name);
                subjectService.englishUpdate(jsonContentString,type,name);
            }
            return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
